//
//  TradeProxyView.m
//  BTCoin
//
//  Created by Robin on 29/03/2018.
//  Copyright © 2018 Robin. All rights reserved.
//

#import "TradeProxyView.h"
#import "TradeProxyTableCell.h"
#import "EntrustInfoModel.h"
#import "NSDate+Util.h"
#import "TradeService.h"
#import "UIAlertController+Block.h"
#import "ShareFunction.h"
#import "MJRefresh.h"

@interface TradeProxyView ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic,assign) NSInteger modelIndex;
@property (nonatomic, strong) UILabel * emptyLabel;
@end

@implementation TradeProxyView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.emptyLabel = [[UILabel alloc] init];
        self.emptyLabel.textColor = color_333333;
        self.emptyLabel.text = @"暂无相关数据";
        self.emptyLabel.font = [UIFont systemFontOfSize:17.0];
        [self addSubview:self.emptyLabel];
        [self.emptyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
        }];
        
        _tableView = [[UITableView alloc] init];
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.tableView registerNib:[UINib nibWithNibName:@"TradeProxyTableCell" bundle:nil] forCellReuseIdentifier:@"TradeProxyTableCell"];
        [self addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.leading.bottom.trailing.equalTo(self);
        }];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            if ([UserInfo isLogin]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:REQUESTCNYPROXYNOTIFICATION object:nil];
            } else {
                [[NSNotificationCenter defaultCenter] postNotificationName:REQUESTLOGINAPPNOTIFICATION object:nil];
                [_tableView.mj_header endRefreshing];
            }
        }];
    }
    
    return self;
}

- (void)updateView {
//    self.emptyLabel.hidden = self.model.tradeProxyArray.count > 0;
//    self.tableView.hidden = self.model.tradeProxyArray.count == 0;
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.model.tradeProxyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *ChannelIdentifier = @"TradeProxyTableCell";
    TradeProxyTableCell *cell = [tableView dequeueReusableCellWithIdentifier:ChannelIdentifier forIndexPath:indexPath];
    
    [self configCell:cell indexPath:indexPath];
    
    return cell;
}

- (void)configCell:(TradeProxyTableCell *)cell indexPath:(NSIndexPath *)indexPath {
    EntrustModel * model = self.model.tradeProxyArray[indexPath.row];
    NSDate * date = [[NSDate alloc] initWithTimeIntervalSince1970:model.fcreateTime.time/1000.0];
    cell.dateLabel.text = [date stringWithDateFormate:@"yyyy-MM-dd HH:mm:ss"];
    
    cell.typeLabel.text = model.fentrustType==0?@"买入":(model.fentrustType==1?@"卖出":@"");
    cell.countLabel.text = [NSString stringWithFormat:@"%ld",model.fcount];
    cell.prizeLabel.text = [NSString stringWithFormat:@"%.4f",model.fprize];
    
    cell.amountLabel.text = [NSString stringWithFormat:@"%ld",model.famount];
    cell.dealAmountLabel.text = [NSString stringWithFormat:@"%ld",model.fcount-model.fleftCount];
    cell.successAmountLabel.text = [NSString stringWithFormat:@"%ld",model.fsuccessAmount];
    
    cell.feesLabel.text = [NSString stringWithFormat:@"%.4f",model.ffees];
    if (model.fcount == model.fleftCount) {
        cell.feesLabel.text = @"0.0000";
    } else {
        float averagePrice = (model.fsuccessAmount / (model.fcount - model.fleftCount));
        cell.feesLabel.text = [NSString stringWithFormat:@"%.4f",averagePrice];
    }
    
    if (model.fstatus == 1 || model.fstatus == 2) {
        if (model.fstatus == 1) {
            cell.statusLabel.text = @"未成交";
        } else if (model.fstatus == 2) {
            cell.statusLabel.text = @"部分成交";
        }
        
        [cell.proxyBtn setTitle:@"撤单" forState:UIControlStateNormal];
        cell.proxyBtn.tag = indexPath.row;
        @WeakObj(self)
        cell.block = ^(NSInteger returnValue) {
            [selfWeak alertToCancelTrade:returnValue];
        };
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 175.0;
}


- (void)alertToCancelTrade:(NSInteger)index {
    self.modelIndex = index;
    [UIAlertController createAlertViewWithTitle:@"确定撤单?" withViewController:[ShareFunction getCurrentVC] withCancleBtnStr:@"取消" withOtherBtnStr:@"确定" withMessage:@"" completionCallback:^(NSInteger index) {
        if (index == 1) {
            [self cancelTrade];
        }
    }];
}

- (void)cancelTrade {
    EntrustModel * model = self.model.tradeProxyArray[self.modelIndex];
    NSDictionary * parDict = @{@"id":@(model.fid)
                               };
    
    [[TradeService sharedTradeService] cancelEntrust:parDict success:^(id responseObject) {
        Loading_Hide(self);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            EntrustInfoModel * userInfo = [[EntrustInfoModel alloc] initWithDictionary:responseObject error:nil];
            
            if (SuccessCode == userInfo.code) {
                [PopupViewHUD showSuccessPopup:userInfo.msg];
                [self.model.tradeProxyArray removeObjectAtIndex:self.modelIndex];
                self.modelIndex = 0;
                [self.tableView reloadData];
            } else {
                [PopupViewHUD showErrorPopup:userInfo.msg];
            }
        }
    } fail:^(NSError *error) {
        Loading_Hide(self);
    }];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
